package com.azr.jesus.service.impl;

import cn.hutool.core.util.StrUtil;
import com.azr.jesus.entity.SysDept;
import com.azr.jesus.mapper.SysDeptMapper;
import com.azr.jesus.service.ISysDeptService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门表 服务实现类
 * @author: Xiong
 * @date: 2022-12-01
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    @Override
    public List<SysDept> findDeptList(String deptName) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> deptIds = new ArrayList<Long>();
        QueryWrapper<SysDept> query = new QueryWrapper<>();
        if (StrUtil.isNotBlank(deptName)) {
            query.like("dept_name", deptName);
        }
        List<SysDept> depts = list(query);
        for (SysDept dept : depts) {
            deptIds.add(dept.getDeptId());
        }
        for (SysDept dept : depts) {
            // 遍历顶级节点的所有子节点
            if (!deptIds.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = (SysDept) it.next();
            if (StrUtil.isNotEmpty(n.getParentId().toString()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }


    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }
}
